package com.boxin.ims.modules.wechat.web.front;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boxin.framework.base.dao.DaoHelper;
import com.boxin.ims.modules.momarketing.common.ProjectUtils;
import com.boxin.ims.modules.momarketing.common.QRCodeUtils;
import com.boxin.ims.modules.momarketing.entity.Coupon;
import com.boxin.ims.modules.momarketing.entity.CouponConfig;
import com.boxin.ims.modules.momarketing.entity.QRCode;
import com.boxin.ims.modules.momarketing.service.CouponConfigService;
import com.boxin.ims.modules.momarketing.service.CouponService;
import com.boxin.ims.modules.wechat.busi.BusinessProcessor;
import com.boxin.ims.modules.wechat.busi.CouponProcessor;
import com.boxin.ims.modules.wechat.busi.DefaultProcessor;
import com.boxin.ims.modules.wechat.busi.ExchangeProcessor;
import com.boxin.ims.modules.wechat.busi.LinktoProcessor;
import com.boxin.ims.modules.wechat.busi.LotteryProcessor;
import com.boxin.ims.modules.wechat.busi.MemberBindProcessor;
import com.boxin.ims.modules.wechat.busi.SceneLotteryProcessor;
import com.boxin.ims.modules.wechat.busi.SeckillQueryProcessor;
import com.boxin.ims.modules.wechat.busi.ShareProcessor;
import com.boxin.ims.modules.wechat.busi.WeatherProcessor;
import com.boxin.ims.modules.wechat.entity.BusinessConfig;
import com.boxin.ims.modules.wechat.entity.EventMessage;
import com.boxin.ims.modules.wechat.entity.ImageMessage;
import com.boxin.ims.modules.wechat.entity.LotteryConfig;
import com.boxin.ims.modules.wechat.entity.LotteryScope;
import com.boxin.ims.modules.wechat.entity.MusicMessage;
import com.boxin.ims.modules.wechat.entity.NewsReply;
import com.boxin.ims.modules.wechat.entity.SeckillConfig;
import com.boxin.ims.modules.wechat.entity.TextMessage;
import com.boxin.ims.modules.wechat.entity.UserBusiness;
import com.boxin.ims.modules.wechat.entity.UserDefine;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.entity.WechatConfig;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.entity.WechatMenu;
import com.boxin.ims.modules.wechat.entity.WechatWelcome;
import com.boxin.ims.modules.wechat.score.service.ScoreExchangeService;
import com.boxin.ims.modules.wechat.service.FriendCircleService;
import com.boxin.ims.modules.wechat.service.LotteryConfigService;
import com.boxin.ims.modules.wechat.service.LotteryScopeService;
import com.boxin.ims.modules.wechat.service.MemberScoreService;
import com.boxin.ims.modules.wechat.service.NewsReplyService;
import com.boxin.ims.modules.wechat.service.RegionService;
import com.boxin.ims.modules.wechat.service.SeckillConfigService;
import com.boxin.ims.modules.wechat.service.UserDefineService;
import com.boxin.ims.modules.wechat.service.WeChatService;
import com.boxin.ims.modules.wechat.service.WechatConfigService;
import com.boxin.ims.modules.wechat.service.WechatDaoHelper;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.boxin.ims.modules.wechat.service.WechatMybatisService;
import com.boxin.ims.modules.wechat.service.WechatWelcomeService;
import com.boxin.ims.modules.wechat.service.share.CircleShareService;
import com.boxin.ims.modules.wechat.service.share.ShareConfigService;
import com.boxin.ims.modules.wechat.service.share.ShareRuleService;
import com.boxin.ims.modules.wechat.utils.MessageProcessorUtils;
import com.boxin.ims.modules.wechat.utils.ScoreUtils;
import com.boxin.ims.modules.wechat.utils.SessionUtils;
import com.boxin.ims.modules.wechat.utils.SpringUtils;
import com.boxin.ims.modules.wechat.utils.WechatMenuUtils;
import com.boxin.ims.modules.wechat.utils.WechatUtils;
import com.boxin.ims.modules.wechat.utils.XMLUtils;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;

@Controller
@RequestMapping(value = Global.MOBILE_SITE_PATH + "/wechat")
public class WeChatMessageController  extends BaseController{
	private final static Logger logger = Logger.getLogger(WeChatMessageController.class);
	
	@Autowired
	WeChatService weChatService;
	
	@Autowired
	RegionService regionService;
	
	@Autowired
	SystemService systemService;
	
	@Autowired
	WechatConfigService wechatConfigService;
	
	@Autowired
	WechatWelcomeService  wechatWelcomeService;
	
	@Autowired
	NewsReplyService newsReplyService;
	
	@Autowired
	DaoHelper daoHelper;
	
	@Autowired
	CouponService couponService;
	
	@Autowired
	WechatMybatisService wechatMybatisService;
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	MemberScoreService memberScoreService;
	
	@Autowired
	CouponConfigService couponConfigService;
	
	@Autowired
	LotteryScopeService lotteryScopeService;
	
	@Autowired
	LotteryConfigService lotteryConfigService;
	
	@Autowired
	ScoreExchangeService scoreExchangeService;
	
	
	@Autowired 
	LotteryProcessor lotteryProcessor;
	
	
	@Autowired
	FriendCircleService friendCircleService;
	
	
	@Autowired
	CircleShareService circleShareService;
	
	
	@Autowired
	ShareConfigService shareConfigService;
	
	@Autowired
	ShareRuleService shareRuleService;
	
	@Autowired
	ShareProcessor shareProcessor;
	
	@Autowired
	ExchangeProcessor exchangeProcessor;
	
	@Autowired
	WeatherProcessor weatherProcessor;
	
	@Autowired
	DefaultProcessor defaultProcessor;
	
	@Autowired
	WechatDaoHelper wechatDaoHelper;
	
	
	@Autowired
	SceneLotteryProcessor sceneLotteryProcessor;
	
	@Autowired
	UserDefineService userDefineService;
	
	@Autowired
	LinktoProcessor linktoProcessor;
	
	
	@Autowired
	CouponProcessor couponProcessor;
	
	@Autowired
	MemberBindProcessor memberBindProcessor;
	
	@Autowired
	SeckillQueryProcessor seckillQueryProcessor;
	
	
	@Autowired
	SeckillConfigService seckillConfigService;
	
	
	@RequestMapping(value = {"chat", ""})
	public void chat(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			
			String method = request.getMethod();
			if("GET".equals(method)){
				valid(request,response,model);
				return;
			}
			
			System.out.println("进入微信消息处理.....");
			String wid	 =  request.getParameter("wid");		//后台设置ID WeChat 的ID
			WeChat weChat = weChatService.get(Long.parseLong(wid));
			String reply = weChat.getRemarks();	//默认回复内容
			User user = weChat.getUser();	//微信平台所属用户
			UserDefine userDefine = userDefineService.getByUserId(user.getId());
			
			//1.获取自己所有服务列表
			
			
			StringBuffer sb = new StringBuffer();
			BufferedReader bReader =   request.getReader();
			String line = "";
			while((line = bReader.readLine()) != null){
				sb.append(line);
			}
			
			logger.debug("接收到的请求内容是："+sb.toString());
			
			
			Map<String,String> map = XMLUtils.xml2Map(sb.toString());
			TextMessage textMessage = new TextMessage(map);
			TextMessage processorMessage = new TextMessage(map);		//供Processor使用
			
			//上行数据
			String upcon = textMessage.getContent();	//用户输入的内容
			String openId = textMessage.getToUserName();	//用户 Open Id
			String wechatId = textMessage.getFromUserName();	//微信公众平台Id
			if(com.thinkgem.jeesite.common.utils.StringUtils.isEmpty(weChat.getWpId())){
				weChat.setWpId(wechatId);
				weChatService.save(weChat);
			}else{
				if(!weChat.getWpId().equals(wechatId)){
					reply = "非法接入.";
					//返回给微信用户的信息
					try {
						textMessage.setContent(reply);
						response.getWriter().print(textMessage.replyMessage() );
						logger.info(textMessage.replyMessage());
					} catch (Exception e) {
						e.printStackTrace();
					}		
					return ;
				}
			}
			
			textMessage.setContent(reply);	//默认自动回复的内容
			reply = textMessage.replyMessage();
			
			
			SessionUtils.addSession(openId, upcon);		//创建会话
			
			
			//判断事件,回复欢迎词
			String MsgType = map.get("xml.MsgType");
			
			if(EventMessage.MSG_TYPE.equals(MsgType)){		//事件类型的处理 ： 
				
				if(EventMessage.EVENT_TYPE_JOIN.equals(map.get("xml.Event"))){	//订阅事件
					
					//添加到会员
					//addWechatMember(user, wpuser);
					
					WechatWelcome wechatWelcome = weChat.getWechatWelcome();
//					//选择默认的欢迎回复内容
					if(MusicMessage.MSG_TYPE.equals(wechatWelcome.getType())){
						MusicMessage musicMessage = new MusicMessage(map);
						musicMessage.setMusicUrl(wechatWelcome.getMusicUrl() );
						musicMessage.setHQMusicUrl(wechatWelcome.getMusicUrl());
						musicMessage.setTitle(wechatWelcome.getTitle());
						musicMessage.setDescription(wechatWelcome.getDescription());
						response.getWriter().print(musicMessage.replyMessage() );
						System.out.println("回复的图文内容:"+musicMessage.replyMessage());
						return ;
						
					}else if(ImageMessage.MSG_TYPE_NEWS.equals(wechatWelcome.getType())){	//回复图文信息
						ImageMessage imageMessage = new ImageMessage(map);
						imageMessage.setArticleCount("1");
						imageMessage.setTitle(wechatWelcome.getTitle());
						imageMessage.setDescription(wechatWelcome.getDescription());
						imageMessage.setPicUrl(wechatWelcome.getPicUrl());
						imageMessage.setUrl(wechatWelcome.getUrl());
						
						
						Map<String,String> params = Maps.newHashMap();
						params.put("welcomeId", wechatWelcome.getId()+"");
						List<NewsReply> newsReplyList = wechatMybatisService.findNewsReply(params);
						response.getWriter().print(imageMessage.replyMessage(newsReplyList));
						System.out.println("回复的图文内容:"+imageMessage.replyMessage());
						return ;
					}else{
						textMessage.setContent(wechatWelcome.getContent());
						response.getWriter().print(textMessage.replyMessage() );
						printReplyLogger(textMessage.replyMessage() );
						return;
					}
					
				}else if(EventMessage.EVENT_TYPE_QUIT.equals(map.get("xml.Event"))){//退订事件
					//删除会员积分，取消会员申请关系
					WechatMember member =	wechatMemberService.getByWechatMemberId(weChat.getUser(), openId);
					if(member != null){
						member.setScore(0);
						wechatMemberService.save(member);
						ScoreUtils.addWechatCancelScore(member,-member.getScore());
					}
					
					//不再删除会员这条记录，只是将其的积分置为0
					//wechatMemberService.deleteByUserIdAndWechatId(weChat.getUser().getId(),openId) ;
					return ;
				}else if(EventMessage.EVENT_CLICK.equals(map.get("xml.Event"))){	//菜单事件---点击事件
					String eventKey = map.get("xml.EventKey");
					if(WechatMenuUtils.BIND_MEMBER_KEY.equals(eventKey)){	//绑定会员的事件
						upcon = "会员申请";
					}else if((WechatMenuUtils.SIGN_MEMBER_KEY.equals(eventKey))){	//签到的事件
						upcon = "签到";
					}else if((WechatMenuUtils.LOTTERY_KEY.equals(eventKey))){	//抽奖
						upcon = "抽奖";
					}else if(WechatMenuUtils.SCORE_EXCHANGE_KEY.equals(eventKey)){	//积分兑换
						upcon = "积分兑换";
					}else if(WechatMenuUtils.SCORE_QUERY_KEY.equals(eventKey)){
						upcon = "积分";
					}else{
						
						WechatMenu menu = 	WechatMenuUtils.getWechatMenuByEventKey(eventKey);
						if(menu != null){
							upcon = menu.getKeywords();
							processorMessage.setContent(upcon);
							logger.debug("菜单Key="+menu.getEventKey()+",关键词:"+menu.getKeywords());
							if(StringUtils.isEmpty(upcon)){
								reply = weChat.getRemarks();
								TextMessage txtMsg = new TextMessage(map);
								txtMsg.setContent(reply);
								response.getWriter().print(txtMsg.replyMessage() );
								printReplyLogger(txtMsg.replyMessage());
								return ;
							}
						}else {
							reply = weChat.getRemarks();
							TextMessage txtMsg = new TextMessage(map);
							txtMsg.setContent(reply);
							response.getWriter().print(txtMsg.replyMessage() );
							printReplyLogger(txtMsg.replyMessage());
							return ;
							
						}
					}
					
				}else if(EventMessage.EVENT_VIEW.equals(map.get("xml.Event"))){		//查看 导航 网址
					String url = map.get("xml.url");
					System.out.println("要访问的URL:"+url);
					url = url +((url.contains("?") ? "&" : "?"))+"openid="+openId;
				} else{
					return ;
				}
				
			}else if(ImageMessage.MSG_TYPE.equals(MsgType)){//微圈分享转发有奖活 
				shareProcessor.setUser(user);
				shareProcessor.setWeChat(weChat);
				shareProcessor.setOpenId(openId);
				shareProcessor.setRequest(request);
				shareProcessor.setResponse(response);
				shareProcessor.setMessageMap(map);
				shareProcessor.setTextMessage(processorMessage);
				
				shareProcessor.process();
				
				return;
				
			}
			
			/////////////////////////纯文本内容的处理//////////////////////////////
			
			if(upcon.equals("秒杀")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				
				linktoProcessor.setTitle("超值秒杀等你拿");
				linktoProcessor.setDesc("点击图片进入超值秒杀,祝您好运!");
				String seckillPic = "seckill.jpg";
				SeckillConfig seckillConfig =	seckillConfigService.getByUserId(user.getId()) ;
				if(seckillConfig!=null && com.thinkgem.jeesite.common.utils.StringUtils.isNotEmpty(seckillConfig.getSeckillPic())){
					seckillPic = seckillConfig.getSeckillPic();
				}
				
				linktoProcessor.setPicUrl("http://www.hdzhx.com/zxims/userfiles/seckill/"+seckillPic+"?t="+System.currentTimeMillis());
				linktoProcessor.setUrl( "http://www.hdzhx.com/zxims/f/wechat/product/seckills?uid="+user.getId() +"&wechatId="+openId);
				
				linktoProcessor.process();
				
			}else if(upcon.startsWith("微会员")){
				
				memberBindProcessor.setUser(user);
				memberBindProcessor.setWeChat(weChat);
				memberBindProcessor.setOpenId(openId);
				memberBindProcessor.setRequest(request);
				memberBindProcessor.setResponse(response);
				memberBindProcessor.setMessageMap(map);
				memberBindProcessor.setTextMessage(processorMessage);
				memberBindProcessor.process();
				return ;
				
			}else if("会员申请".equals(upcon) ){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				String title = "微会员申请";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberTitle())){
					title = userDefine.getRegMemberTitle();
				}
				String desc = "点击图片进入微会员申请页面，成为我们的会员后，您将可以参与各种优惠活动以及享受更高级的服务,谢谢!";
				if(userDefine != null && StringUtils.isNotEmpty(userDefine.getRegMemberDesc())){
					desc = userDefine.getRegMemberDesc();
				}
				
				linktoProcessor.setTitle(title);
				linktoProcessor.setDesc(desc);
				String picName = "reg.jpg";
				if(userDefine!=null && StringUtils.isNotEmpty(userDefine.getRegMemberPic())){
					picName = userDefine.getRegMemberPic();
				}
				linktoProcessor.setPicUrl("http://www.hdzhx.com/zxims/userfiles/images/"+picName+"?t="+System.currentTimeMillis());
				linktoProcessor.setUrl( "http://www.hdzhx.com/zxims/f/wechat/bind/"+user.getId() +"?wechatId="+openId);
				linktoProcessor.process();
				
				return;
			}else if(upcon.contains("登录")){
				
				linktoProcessor.setUser(user);
				linktoProcessor.setWeChat(weChat);
				linktoProcessor.setOpenId(openId);
				linktoProcessor.setRequest(request);
				linktoProcessor.setResponse(response);
				linktoProcessor.setMessageMap(map);
				linktoProcessor.setTextMessage(processorMessage);
				
				linktoProcessor.setTitle("微会登录");
				linktoProcessor.setDesc("");
				linktoProcessor.setPicUrl("http://www.hdzhx.com/zxims/userfiles/images/reg.jpg?t="+System.currentTimeMillis());
				linktoProcessor.setUrl( "http://www.hdzhx.com/zxims/f/wechat/login/"+user.getId() +"?wechatId="+openId);
				
				linktoProcessor.process();
				
				return ;
				
			}else{//未找到以上固定的关键词，则用用户自定义的
				
				//服务性的数据处理
				BusinessProcessor processor =	MessageProcessorUtils.getBusinessProcessorByKeywords(weChat, processorMessage, map, request, response);
				if(processor!=null){
					processor.process();
					return;
				}else{
					defaultProcessor.setRequest(request);
					defaultProcessor.setUser(user);
					defaultProcessor.setWeChat(weChat);
					defaultProcessor.setOpenId(openId);
					defaultProcessor.setRequest(request);
					defaultProcessor.setResponse(response);
					defaultProcessor.setMessageMap(map);
					defaultProcessor.setTextMessage(processorMessage);
					defaultProcessor.process();
				}
				
				
				return  ;
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-26  上午10:26:00
	 * @function <p> 回复内容 </p>
	 * @param content
	 */
	private void printReplyLogger(String content){
		logger.debug("回复的全内容是:"+content);
	}
	
	@RequestMapping(value =  "valid")
	public void valid(HttpServletRequest request, HttpServletResponse response, Model model){
		
		System.out.println("微信请认证消息.....");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = 	   request.getParameter("nonce");
		String wid		 =  request.getParameter("wid");		//后台设置ID WeChat 的ID
		String echostr = request.getParameter("echostr");
		String Token = "";
		if(!StringUtils.isBlank(wid)){  //从平台中获取Token 进行绑定
			try {
				WeChat weChat  = weChatService.get(Long.parseLong(wid));
				if(weChat!=null){
					Token  = weChat.getToken();
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("查找ID为:"+wid+"的用户Token失败!");
			}
		}
		
		try {
			
			String[] ArrTmp = { Token, timestamp, nonce };
			Arrays.sort(ArrTmp);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < ArrTmp.length; i++) {
				sb.append(ArrTmp[i]);
			}
			String pwd = Encrypt(sb.toString());
			
			logger.debug("pwd=="+pwd);
			logger.debug("signature=="+signature);
			logger.debug("echostr=="+echostr);
			
			if(pwd.equals(signature)){
				if(!"".equals(echostr) && echostr != null){
					response.getWriter().write(echostr);
					logger.debug("绑定成功...");
				}else{
					response.getWriter().write("非法签名,认证失败!");
					logger.debug("绑定失败...非法签名,认证失败!");
				}
			}else{
				response.getWriter().write("非法签名,认证失败!");
				logger.debug("非法签名,认证失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-6-21  上午10:09:30
	 * @function <p> 图片或声音的资源文件 URL </p>
	 * @param request
	 * @param response
	 * @return
	 */
	
	@RequestMapping(value =  "vr")
	public String viewResource(HttpServletRequest request, HttpServletResponse response){
		
		String rid = request.getParameter("rid");
		String fileName = request.getParameter("fname");
		String wid = request.getParameter("wid");		// 
		String vtype = request.getParameter("vtype");	//访问类型   reply和welcome
		
		WechatConfig config = 	wechatConfigService.get(Long.parseLong(wid));
		
		String filepath = "";
		String type = ImageMessage.MSG_TYPE_NEWS;
		if("reply".equals(vtype)){	//多图文时 查NewsReply表中的资源
			NewsReply newsReply = 	newsReplyService.get(Long.parseLong(rid));
			filepath = newsReply.getFilePath();
		}else{
			WechatWelcome welcome =  config.getWeChat().getWechatWelcome();
			type = welcome.getType();
			filepath = welcome.getFilePath();
		}
		
		logger.debug("访问要下载的图片文件位置是为 filepath :"+filepath);
		
		if(MusicMessage.MSG_TYPE.equals(type)){	//音乐
			try {
				//1.回复的声音文件
				 File file = new File(filepath);
				 OutputStream outputStream = response.getOutputStream();
				 InputStream inputStream = new FileInputStream(file);
				 
				 response.setContentType("audio/mp3");
				 
				 byte[] buffer = new byte[1024];
				 int i = -1;
				 while ((i = inputStream.read(buffer)) != -1) {
				  outputStream.write(buffer, 0, i);
				 }
				 outputStream.flush();
				 outputStream.close();
				 inputStream.close();
				 outputStream = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
		}else if(ImageMessage.MSG_TYPE_NEWS.equals(type)){
			try {
				
				//2.回复的图文
				File file = new File(filepath);
//				BufferedImage image = 	ImageIO.read(file);
				
				OutputStream outputStream = response.getOutputStream();
//				ImageIO.write(image, "JPEG", out);
//				
//				out.flush();
//				out.close();
				 String contentType = "image/jpeg";
				 if(filepath.toLowerCase().endsWith("gif")){
					 contentType = "image/gif";
				 }
				 response.setContentLength((int)file.length());
				 response.setContentType(contentType+";charset=UTF-8"); 
				 InputStream inputStream = new FileInputStream(file);
				 byte[] buffer = new byte[1024];
				 int i = -1;
				 while ((i = inputStream.read(buffer)) != -1) {
				  outputStream.write(buffer, 0, i);
				 }
				 outputStream.flush();
				 outputStream.close();
				 inputStream.close();
				 outputStream = null;
				
				 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
		
		return null;
	}
	
	
	
	
	
	@RequestMapping(value =  "vrqr")
	public String viewQRCode(HttpServletRequest request, HttpServletResponse response){
		String strId = request.getParameter("id");
		try {
			Long id = Long.parseLong(strId);
			Coupon coupon = couponService.get(id);
			QRCode qrCode = coupon.getQrCode();
			request.setAttribute("qrcodeImg", QRCodeUtils.getQRCodeURL(qrCode.getId()));
			request.setAttribute("coupon", coupon);
			return "modules/wechat/couponQRCode";
		} catch (Exception e) {
			
		}
		
		return null;
	}
	
	
	
	public String Encrypt(String strSrc) {
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); //to HexString
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
	public boolean isChinese(String str){  
	     boolean result=false;  
	     for (int i = 0; i < str.length(); i++){  
	          int chr1 = (char) str.charAt(i);  
	          if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)  
	              result = true;  
	          } 
	     }  
	     return result;  
	} 
	
	
	/**
	 * @author Jakemanse
	 * @time 2013-9-8  下午11:26:44
	 * @function <p> 添加微信至会员 </p>
	 * @param user
	 * @param wechatId
	 */
	public WechatMember addWechatMember(User user,String wechatId){
		
		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(user, wechatId);
		if(wechatMember == null){	//不存在则添加
			wechatMember = new WechatMember();
			wechatMember.setUser(user);
			wechatMember.setWechatId(wechatId);
			wechatMember.setScore(1);
			wechatMemberService.save(wechatMember);
			return wechatMember;
		}

		return null;
	}
	
	
	
	
	

}
